﻿using System;
using System.Collections.Generic;

using Fuse8.DomainFramework.Domain;
using Fuse8.DomainFramework.Configuration.Cache;

namespace Fuse8.DomainFramework.CacheService
{
    /// <summary>
    /// 
    /// </summary>
    public class CacheFacade
    {
        #region Singleton

        private static readonly object _syncRoot = new object();

        private static volatile CacheFacade _instance;

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static CacheFacade GetInstance()
        {
            if (_instance == null)
            {
                lock (_syncRoot)
                {
                    if (_instance == null)
                    {
                        _instance = new CacheFacade();
                    }
                }
            }

            return _instance;
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <typeparam name="TEntityKey"></typeparam>
        /// <typeparam name="TDependableEntity"></typeparam>
        /// <typeparam name="TDependableEntityKey"></typeparam>
        /// <returns></returns>
        public CacheFacade RegisterTypeDependency<TEntity, TEntityKey, TDependableEntity, TDependableEntityKey>()
            where TEntity : class, IEntityObject<TEntityKey>, new()
            where TEntityKey : IComparable<TEntityKey>, IEquatable<TEntityKey>
            where TDependableEntity : class, IEntityObject<TDependableEntityKey>, new()
            where TDependableEntityKey : IComparable<TDependableEntityKey>, IEquatable<TDependableEntityKey>
        {
            //for initialization purpose only
            CacheServiceFactory<TEntity, TEntityKey>.GetCacheService();
            CacheServiceFactory<TDependableEntity, TDependableEntityKey>.GetCacheService();
            
            var cacheService = CacheServiceFactory<TEntity, TEntityKey>.GetCacheService();
            if (cacheService != null)
            {
                var dependencies = cacheService.CacheOptions.Dependencies ?? new List<string>();

                dependencies.Add(typeof(TDependableEntity).Name);

                cacheService.CacheOptions.Dependencies = dependencies;
            }

            return this;
        }
    }
}
